// html2canvas方式下载证书
import html2canvas from 'html2canvas';

/**
 * 证书下载工具类
 */
class CertificateDownloader {
  /**
   * 下载单个证书
   * @param {Object} certificate - 证书数据
   * @returns {Promise}
   */
  static async downloadSingleCertificate(certificate) {
    return new Promise(async (resolve, reject) => {
      try {
        // 创建临时DOM元素用于渲染证书
        const tempDiv = document.createElement('div');
        tempDiv.style.position = 'absolute';
        tempDiv.style.left = '-9999px';
        tempDiv.style.width = '500px';
        tempDiv.style.height = '750px';

        // 构建证书内容
        const templateDto = certificate.certificateTemplateDto;
        if (!templateDto) {
          reject(new Error('证书模板数据缺失'));
          return;
        }

        // 设置样式
        tempDiv.style.backgroundColor = templateDto.backgroundColor || 'white';
        tempDiv.style.border = templateDto.borderColor 
          ? `1px solid ${templateDto.borderColor}` 
          : 'none';

        if (templateDto.backgroundUrl) {
          tempDiv.style.backgroundImage = `url(${this.resolveImageUrl(
            templateDto.backgroundUrl
          )})`;
          tempDiv.style.backgroundSize = 'cover';
          tempDiv.style.backgroundRepeat = 'no-repeat';
          tempDiv.style.backgroundPosition = 'center';
        }

        tempDiv.style.display = 'flex';
        tempDiv.style.flexDirection = 'column';
        tempDiv.style.justifyContent = 'center';
        tempDiv.style.padding = '20px';
        tempDiv.style.boxSizing = 'border-box';

        // 添加字段内容
        const fields = templateDto.certificateFieldList || [];
        fields.forEach((field) => {
          if (field.fieldKey && field.fieldLabel) {
            const textDiv = document.createElement('div');
            textDiv.textContent = this.getFieldContent(certificate, field);
            Object.assign(textDiv.style, {
              fontFamily: field.fontFamily || 'SimHei',
              fontSize: (field.fontSize || 18) + 'px',
              color: field.fontColor || '#000000',
              fontWeight: field.fontWeight || 'normal',
              fontStyle: field.italic === 'true' ? 'italic' : 'normal',
              textDecoration: field.underline === 'true' ? 'underline' : 'none',
              textAlign: field.textAlign || 'center',
              lineHeight: field.lineHeight || 1.2,
              letterSpacing: (field.letterSpacing || 0) + 'px',
              margin: '10px 0',
              padding: '5px',
            });
            tempDiv.appendChild(textDiv);
          }
        });

        document.body.appendChild(tempDiv);

        // 使用 html2canvas 生成图片
        const canvas = await html2canvas(tempDiv, {
          backgroundColor: null,
          scale: 2,
          useCORS: true,
          allowTaint: true,
          logging: false,
          width: tempDiv.offsetWidth,
          height: tempDiv.offsetHeight,
        });

        // 转换为图片并下载
        const imageData = canvas.toDataURL('image/png', 1.0);
        const link = document.createElement('a');
        const studentName = certificate.studentName || '证书';
        link.download = `${studentName}-证书.png`;
        link.href = imageData;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        document.body.removeChild(tempDiv);

        resolve();
      } catch (error) {
        reject(error);
      }
    });
  }

  /**
   * 获取字段内容
   * @param {Object} certificate - 证书数据
   * @param {Object} field - 字段配置
   * @returns {String} 字段内容
   */
  static getFieldContent(certificate, field) {
    if (!certificate) return '未填写';

    switch (field.fieldKey) {
      case 'studentName':
        return certificate.studentName || field.exampleOne || '未填写';
      case 'issueDate':
        return certificate.issueDate || field.exampleOne || '未填写';
      case 'validityEnd':
        return certificate.validityEnd || field.exampleOne || '未填写';
      case 'certificateNo':
        return certificate.certificateNo || field.exampleOne || '未填写';
      case 'createdBy':
        return certificate.createdBy || field.exampleOne || '未填写';
      default:
        if (certificate[field.fieldKey]) {
          return certificate[field.fieldKey];
        }
        return field.exampleOne || '未填写';
    }
  }

  /**
   * 解析图片URL
   * @param {String} url - 图片URL
   * @returns {String} 完整URL
   */
  static resolveImageUrl(url) {
    if (url.startsWith('http://') || url.startsWith('https://')) {
      return url;
    }

    if (url.startsWith('/')) {
      return `/api${url}`;
    }

    return `/api/${url}`;
  }

  /**
   * 批量下载证书
   * @param {Array} certificates - 证书数组
   * @returns {Promise}
   */
  static async downloadCertificates(certificates) {
    if (certificates.length === 0) {
      throw new Error('未获取到证书信息');
    }

    // 对每个证书执行下载操作
    for (let i = 0; i < certificates.length; i++) {
      const cert = certificates[i];
      await this.downloadSingleCertificate(cert);
    }
  }
}

export default CertificateDownloader;